//
//  JMRegisterTVController.m
//  jiMuOperate
//
//  Created by 胡梅方 on 16/4/26.
//  Copyright © 2016年 jinXinFengLi. All rights reserved.
//

#import "JMRegisterTVController.h"
#import "JMCellView.h"
#import "JMTextField.h"
#import "JMResterInfo.h"
#import "JMRegisterReturn.h"
#import "JMTableVController.h"
#import "JMEquipmentTVController.h"
#import "JMTeamTVController.h"
#import "JMHomeVController.h"
#import "JMStagemenVController.h"
#import "JMMembersVController.h"
#import "JMTaskTVController.h"
#import "JMReleaseStrVController.h"

@interface JMRegisterTVController ()<UITextFieldDelegate>

@end

@implementation JMRegisterTVController
{
    UITextField* _registerfield;
    UITextField* _newPasswordfield;
    UITextField* _verifield;
    UITextField* _invitefield;
    UIButton* _verifyBtn;
    UIButton *checkbut;
    UIButton *protcolbut;
    UIButton *registerbut;
    NSInteger currentTime;
    NSTimer *timer;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.navigationItem.title = @"注册";

    [self setupOther];//创建tableView
    [self createButton];
    [self addPolicyView];
}

-(void)setupOther
{
    self.tableView.scrollEnabled = NO;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    self.tableView.tableHeaderView = view;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = BACKCOLOR;
    UITapGestureRecognizer *singleRecognizer;
    singleRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTapFrom)];
    singleRecognizer.numberOfTapsRequired = 1;
    [self.tableView addGestureRecognizer:singleRecognizer];
    
}
- (void)handleSingleTapFrom
{
    [_registerfield resignFirstResponder];
    [_verifield resignFirstResponder];
    [_newPasswordfield resignFirstResponder];
    [_invitefield resignFirstResponder];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"LoginCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    CGFloat imageH = 40;
    UIImageView *lineImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,50, 320, 1)];
    lineImg.image = [UIImage imageNamed:@"halvingline_2"];
    [cell.contentView addSubview:lineImg];
    lineImg.frame = [ToolViewAndData MyAutoLayout:lineImg];
   
    UIImageView *describImg = [[UIImageView alloc]initWithFrame:CGRectMake(10, 15, imageH/2, imageH/2)];
    describImg.frame = [ToolViewAndData MyAutoLayout:describImg];
    [cell.contentView addSubview:describImg];
    if (indexPath.row == 0) {
        describImg.image = [UIImage imageNamed:@"registerPhone"];
        if (!_registerfield) {
            _registerfield = [self addRegisterFieldWithFrame:CGRectMake(imageH, 0, imageH*6, CELLHIGHT)];
            
            [cell.contentView  addSubview:_registerfield];
        }
        

    }else if(indexPath.row == 1){
          describImg.image = [UIImage imageNamed:@"aut_ico_verification code"];
 
  
        UIButton *sendMessagebut = [[UIButton alloc] initWithFrame:CGRectMake(210, 10,100, imageH-10)];
        
        sendMessagebut.clipsToBounds = YES;
        sendMessagebut.layer.cornerRadius = 3.f;//设置边角圆弧的半径，
        [sendMessagebut setTitle:@"发送验证码" forState:UIControlStateNormal];
        sendMessagebut.titleLabel.font = [UIFont systemFontOfSize: 12];
        
        [sendMessagebut setBackgroundImage:[UIImage imageNamed:@"Send_verification_code_btn"] forState:UIControlStateNormal];
        _verifyBtn = sendMessagebut;
        [sendMessagebut addTarget:self action:@selector(verifyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:sendMessagebut];
        if (!_verifield) {
            
            _verifield = [self addVeriFieldWithFrame:CGRectMake(imageH, 0, 180,50)];
            [cell.contentView  addSubview:_verifield];
        }
    }else if(indexPath.row == 2){
           describImg.image = [UIImage imageNamed:@"aut_ico_password"];
        if (!_newPasswordfield) {
            
            _newPasswordfield = [self addNewPasswordFieldWithFrame:CGRectMake(imageH, 0, imageH*6, 50)];
            [cell.contentView  addSubview:_newPasswordfield];
        }
        
    }else if(indexPath.row == 3){
          describImg.image = [UIImage imageNamed:@"aut_ico-Invitation code"];
        if (!_invitefield) {
            
            _invitefield = [self addIvitecodeFieldWithFrame:CGRectMake(imageH, 0, imageH*6, 50)];
            [cell.contentView  addSubview:_invitefield];
        }
    }
    
    return [JMCellView setupCell:cell HideLine:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CELLHIGHT;
}

- (JMTextField *)addRegisterFieldWithFrame:(CGRect)frame
{
    //用户名
    JMTextField *textField = [JMTextField createTextFieldWithFrame:frame
                                                              Font:FONTSIZE
                                                       Placeholder:@"输入您11位的手机号码"
                                                   SecureTextEntry:NO
                                                         TextColor:[UIColor blackColor]];
    textField.keyboardType =  UIKeyboardTypePhonePad;
    textField.delegate = self;
    textField.frame =  [ToolViewAndData MyAutoLayout:textField];
    return  textField;
    
}

- (JMTextField *)addVeriFieldWithFrame:(CGRect)frame
{
    //密码
    JMTextField  *passWord= [JMTextField createTextFieldWithFrame:frame
                                                             Font:FONTSIZE
                                                      Placeholder:@"请输入验证码"
                                                  SecureTextEntry:NO
                                                        TextColor:[UIColor blackColor]];
    
    passWord.frame = [ToolViewAndData MyAutoLayout:passWord];
    
    passWord.delegate = self;
    return  passWord;
}
- (JMTextField *)addNewPasswordFieldWithFrame:(CGRect)frame
{
    //密码
    JMTextField  *passWord= [JMTextField createTextFieldWithFrame:frame
                                                             Font:FONTSIZE
                                                      Placeholder:@"请输入密码,6-16个字符,含字母,数字"
                                                  SecureTextEntry:YES
                                                        TextColor:[UIColor blackColor]];
    
    passWord.frame = [ToolViewAndData MyAutoLayout:passWord];
    
    passWord.delegate = self;
    return  passWord;
}
- (JMTextField *)addIvitecodeFieldWithFrame:(CGRect)frame
{
    //密码
    JMTextField  *inViteCode= [JMTextField createTextFieldWithFrame:frame
                                                             Font:FONTSIZE
                                                      Placeholder:@"请输入邀请码"
                                                  SecureTextEntry:NO
                                                        TextColor:[UIColor blackColor]];
    
    inViteCode.frame = [ToolViewAndData MyAutoLayout:inViteCode];
    
    inViteCode.delegate = self;
    return  inViteCode;
}

#pragma mark - 创建textField

#pragma mark - 创建登陆注册按钮
- (void)createButton{
    
    CGFloat btnX = 300;
    CGFloat btnH = 40;
    
    
    UIButton* registerBtn = [ARC createButtonWithFrame:CGRectMake(30,btnX, 260, btnH)
                                               Target:self
                                                  Sel:@selector(registerBtnClick:)
                                                Title:@"注册"];
    
    [registerBtn setBackgroundImage:[UIImage imageNamed:@"logoin_btn"] forState:UIControlStateNormal];
    registerBtn.frame = [ToolViewAndData MyAutoLayout:registerBtn];
    [registerBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
    registerBtn.tintColor=[UIColor whiteColor];
    [self.view addSubview:registerBtn];
    
    
    UIButton* testbtn = [ARC createButtonWithFrame:CGRectMake(0,400, SCREEN_WIDTH, 100)
                                            Target:self
                                               Sel:@selector(testfff:)
                                             Title:nil];

    [testbtn setBackgroundImage:[UIImage imageNamed:@"  "] forState:UIControlStateNormal];
    [self.view addSubview:testbtn];
    
    
    
}

-(void)testfff:(UIButton*)btn
{
    NSLog(@"fgfhgfj");

//    JMEquipmentTVController *svc = [[JMEquipmentTVController alloc]init];
//    [self.navigationController pushViewController:svc animated:YES];
//    JMHomeVController *teamVc = [[JMHomeVController alloc]init];
//    [self.navigationController pushViewController:teamVc animated:YES];
    JMReleaseStrVController *stateVc = [[JMReleaseStrVController alloc]init];
    [self.navigationController pushViewController:stateVc animated:YES];
    
}



-(void)verifyBtnClick:(UIButton*)btn
{
    
    if (_registerfield.text&&![ToolViewAndData isMobileNumber:_registerfield.text]) {
        SHOWALERT(@"请输入正确的手机号码");
        return;
    }
    
    [self requestVerifyCodeWithPhone:_registerfield.text userType:@"register" token:@""];
}
- (void)requestVerifyCodeWithPhone:(NSString *)phone userType:(NSString *)userType token:(NSString *)token
{
    if(!phone.length){
        return;
    }
//    GET api/Common/SendTelCode?Tel={Tel}&Type={Type}&Token={Token}
    NSString *url = [NSString stringWithFormat:@"%@?Tel=%@&Type=%@&Token=%@",JMURLVerifyCode,phone,userType,token];
    NSArray *arrayR = @[@"",url,@"GET"];
    [Request startRequestWithArray:arrayR FinishedBlock:^(NSData *data) {
        NSDictionary *dictR = [JMData dictAndTestData:data];
        JMResterInfo *resterInfo = [JMResterInfo objectWithKeyValues:dictR];
        if ([resterInfo.State intValue]>=0) {
            currentTime = 60;
            NSString *str = [NSString stringWithFormat:@"%ld秒后重新获取",(long)currentTime];
            
            [_verifyBtn setTitle:str forState:UIControlStateNormal];
            
            timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownTime) userInfo:nil repeats:YES];
            
//        }else if(([resterInfo.State intValue] == -100)){
//            SHOWALERT(@"该手机号已被注册,请重新输入");
        }else{
            NSString *str = @"重新获取验证码";
            [_verifyBtn setTitle:str forState:UIControlStateNormal];
            [timer invalidate];
            SHOWALERT(resterInfo.Msg);
            
        }
        
    } FailBlock:^(NSString *string) {
        //        [timer invalidate];
        SHOWALERT(@"服务器繁忙，请梢后重试");
    }];
    
}
-(void)countDownTime
{
    currentTime--;
    NSString *str = [NSString stringWithFormat:@"%ld秒后重新获取",(long)currentTime];
    
    [_verifyBtn setTitle:str forState:UIControlStateNormal];
    _verifyBtn.userInteractionEnabled = NO;
    if (currentTime <= 0) {
        [timer invalidate];
        [_verifyBtn setTitle: @"获取短信验证码" forState:UIControlStateNormal];
        [_verifyBtn setEnabled:YES];
    }
}

-(void)registerBtnClick:(UIButton*)btn
{
    if (_registerfield.text&&![ToolViewAndData isMobileNumber:_registerfield.text]) {
        SHOWALERT(@"请输入正确的手机号码");
        return;
    }
    if (_newPasswordfield.text.length <6) {
        SHOWALERT(@"密码不能低于6位");
        return;
    }

    if (!checkbut.selected) {
        SHOWALERT(@"您还未同意服务条款协议");
        return;
    }

    [self TelNo:_registerfield.text Pwd:_newPasswordfield.text TelCode:_verifield.text ExtenderKey:_invitefield.text];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [textField resignFirstResponder];
    return YES;
    
}


- (void)addPolicyView
{
    CGFloat reguBX = 0;
    CGFloat reguBH = 30;
    CGFloat reguBY = 275;
    CGFloat reguBW = (SCREEN_WIDTH - reguBX)/2;
    CGRect regulationBtnR = CGRectMake(reguBX, reguBY, reguBW, reguBH);
    
    UIButton *regulationBtn = [[UIButton alloc]initWithFrame:regulationBtnR];
    checkbut = regulationBtn;
    regulationBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    regulationBtn.tintColor = [UIColor grayColor];
    regulationBtn.selected = YES;
    [regulationBtn setTitle:@"我已阅读并同意" forState:UIControlStateNormal];
    [regulationBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [regulationBtn setImage:[UIImage imageNamed:@"aut_ico_agree"]
                   forState:UIControlStateNormal];
    [regulationBtn setImage:[UIImage imageNamed:@"aut_ico_agree"]
                   forState:UIControlStateSelected];
    [regulationBtn addTarget:self action:@selector(regulationBtnClick:)
            forControlEvents:UIControlEventTouchUpInside];
    [regulationBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    
    CGFloat reguB2X = CGRectGetMaxX(regulationBtnR);
    CGFloat reguB2Y = reguBY;
    CGFloat reguB2W = SCREEN_WIDTH - reguB2X;
    CGFloat reguB2H = reguBH;
    CGRect  reguB2R = CGRectMake(reguB2X, reguB2Y, reguB2W, reguB2H);
    
    UIButton *regulationBtn2 = [[UIButton alloc]initWithFrame:reguB2R];
    regulationBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    regulationBtn2.titleLabel.font = regulationBtn.titleLabel.font;
    [regulationBtn2 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [regulationBtn2 setTitle:@"《服务条款协议》" forState:UIControlStateNormal];
    [regulationBtn2 addTarget:self action:@selector(gotoRegulationWV:) forControlEvents:UIControlEventTouchUpInside];
    [regulationBtn2 setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    
    [self.view addSubview:regulationBtn];
    [self.view addSubview:regulationBtn2];
}

- (void)regulationBtnClick:(UIButton *)regulationBtn
{
    protcolbut.selected = !regulationBtn.isSelected;
    
}
-(void)gotoRegulationWV:(UIButton*)btn{
    
}


//*注册
- (void)TelNo:(NSString *)phone Pwd:(NSString *)pwd TelCode:(NSString *)telcode ExtenderKey:(NSString *)extenderKey
{
    
    NSString *urlRe = [NSString stringWithFormat:@"%@",JMURLRegister];
    NSDictionary *dictRe = [JMData TelNo:phone Pwd:pwd TelCode:telcode ExtenderKey:extenderKey];
    
    NSString *strAry = [JMData stringWithDict:dictRe];
    NSArray *aryRe = @[strAry,urlRe];
    [Request startRequestWithArray:aryRe FinishedBlock:^(NSData *data) {
        NSDictionary *dictR = [JMData dictAndTestData:data];
        JMRegisterReturn *registerReturn = [JMRegisterReturn objectWithKeyValues:dictR];
        if ([registerReturn.State intValue]>0) {
             SHOWALERT(@"注册成功，请登录");
            JMTableVController *loginVc = [[JMTableVController alloc]init];
            [self.navigationController pushViewController:loginVc animated:YES];
        }else{
            SHOWALERT(dictR[@"Msg"]);
            
            return ;
        }
        
        
    } FailBlock:^(NSString *string) {
        [MBProgressHUD showError:@"注册失败，请梢后重试"];
    }];
    
}

#pragma mark - 禁止屏幕旋转
SHOULDAutorotate(YES)


@end
